package common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 字节数组与对象之间相互转换的方法定义
 *
 * @author Eugene-Forest
 */
public class Translate {

    /**
     * 对象转换为字节数组形式，实现对象的序列化
     *
     * @param obj 为待转换对象
     * @return 字节数组
     */
    public static byte[] objectToByte(Object obj) {
        byte[] buffer = null;

        try {
            //字节数组输出流
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            //对象输出流
            ObjectOutputStream oo = new ObjectOutputStream(bo);
            oo.writeObject(obj);
            buffer = bo.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * 字节数组转换为对象
     *
     * @param buffer 待转换字节数组
     * @return 对象
     */
    public static Object byteToObject(byte[] buffer) {
        Object obj = null;
        try {
            ByteArrayInputStream bi = new ByteArrayInputStream(buffer);
            ObjectInputStream oi = new ObjectInputStream(bi);
            obj = oi.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

}
